package crazymakercircle;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: DRevelation
 * @Date: 2021/6/29 15:25
 */
@Slf4j
public class PlusTest {

    private final int MAX_TREAD = 10;
    private final int MAX_TURN = 1000;

    @Test
    public void testNoSafePlus() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(MAX_TREAD);
        NoSafePlus noSafePlus = new NoSafePlus();
        Runnable r = () -> {
            for (int i = 0; i < MAX_TURN; i++) {
                noSafePlus.selfPlus();
            }
            countDownLatch.countDown();
        };
        for (int i = 0; i < MAX_TREAD; i++) {
            new Thread(r).start();
        }
        countDownLatch.await();
        log.info("理论结果：" + MAX_TURN * MAX_TREAD);
        log.info("实际结果：" + noSafePlus.getAmount());
        log.info("差距是：" +
                (MAX_TURN * MAX_TREAD - noSafePlus.getAmount()));

    }

    class NoSafePlus {
        private int counter = 0;

        public void selfPlus() {
            counter++;
        }

        public int getAmount() {
            return counter;
        }
    }

    class SafePlus {
        private final AtomicInteger counter = new AtomicInteger(0);

        public void selfPlus() {
            counter.incrementAndGet();
        }

        public int getAmount() {
            return counter.get();
        }
    }
}
